// import tableBody from 'element-ui/packages/table/src/table-body'
import { Scrollbar } from 'element-ui'

export default function (table) {
    // 拿到tableBody这个内置组件
    const tableBody = table.components.TableBody
    // 重写handleScroll，手动触发 @scroll
    Scrollbar.methods.oldHandleScroll = Scrollbar.methods.handleScroll
    Scrollbar.methods = {
        ...Scrollbar.methods,
        handleScroll() {
            this.$emit('tableScroll')
            this.oldHandleScroll()
        },
    }
    // 修改el-table的计算属性，返回更深层的盒子
    table.computed = {
        ...table.computed,
        bodyWrapper() {
            if (this.data.length === 0) {
                // 单独处理空状态
                const table = this.$refs.bodyWrapper.querySelector('table')
                const view = this.$refs.bodyWrapper.querySelector('.el-scrollbar__view')
                const empty = this.$refs.bodyWrapper.querySelector('.el-table__empty-block')
                const newEmpty = empty.cloneNode(true)
                view.style.height = "100%"
                table.style.height = "1px"
                newEmpty.style.position = 'absolute';
                empty.remove()
                view.append(newEmpty)
            }
            return this.$refs.bodyWrapper.querySelector('.el-scrollbar__wrap')
        },
    }
    // 重写table-body组件的render，在外层套了el-scrollbar
    tableBody.oldRender = tableBody.render
    tableBody.computed = {
        ...tableBody.computed,
    }
    tableBody.render = function (h) {
        this.$nextTick(() => {
            // 由于el-table传递给table-body的attr被el-scroll截获导致el-scroll的style不对，所以需要在转换成真实dom后将正确的值重新赋值回来
            this.$el.style.width = '100%'
        })
        // 拿到tableBody的原始VNode
        const vNode = tableBody.oldRender.call(this, h)
        // return vNode
        // 判断是不是fixed-table,是则不添加scrollbar
        if (this.fixed) {
            return vNode
        } else {
            vNode.data.style = { ...this.$vnode.data.style, ...vNode.data.style } // 拿到el-table组件传递给table-body组件的attrs
            return h(
                'el-scrollbar',
                {
                    style: {
                        height: '100%',
                    },
                    on: {
                        tableScroll: this.$parent.onScroll || this.$parent.syncPostion, // 旧版本调用syncPostion，高级版本调用onScroll
                    },
                    class: 'el-table-scrollbar', // 添加自定义类名，用来提高虚拟滚动条的z-index以防止被fixed-table遮挡
                },
                [vNode]
            )
        }
    }

    table.components = {
        ...table.components,
        TableBody: tableBody,
    }
    return table

    //   建议添加在全局的样式
    // 让el-table组件的滚动条动态渲染为0
    //   .el-scrollbar__wrap::-webkit-scrollbar {
    //     display: none;
    //   }

    //  让美化后的el-table的滚动条不被遮挡
    //   .el-table-scrollbar .el-scrollbar__bar {
    //     z-index: 999;
    //   }
}
